package pl.edu.agh.ki.ewywiadowka.client.windows.secretary;

import java.util.LinkedList;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;

import pl.edu.agh.ki.ewywiadowka.client.Const;
import pl.edu.agh.ki.ewywiadowka.client.EWywiadowka;
import pl.edu.agh.ki.ewywiadowka.client.Const.Error.TeacherRegisterMsg;
import pl.edu.agh.ki.ewywiadowka.client.dto.SubjectDTO;
import pl.edu.agh.ki.ewywiadowka.client.dto.TeacherDTO;
import pl.edu.agh.ki.ewywiadowka.client.windows.GenericWindow;

public class ModifyTeacherWindow extends RegisterTeacherWindow implements ClickHandler {
	
	private TeacherDTO _teacher = null;

	public ModifyTeacherWindow(EWywiadowka wywiadowka, TeacherDTO teacher) {
		super(wywiadowka);
		
		_teacher = teacher;
		
		_nameTextBox.setText(teacher.name);
		_surnameTextBox.setText(teacher.surname);
		_addressTextBox.setText(teacher.address);
		_telephoneTextBox.setText(teacher.telephone.toString());
		//_emailTextBox.setText(teacher.user.email);
		//_loginTextBox.setText(teacher.user.login);
		//_passTextBox.setText(teacher.user.pass);
		
		_okButton.setText("Modyfikuj");
	}
	
	public void teacherModify() {
		LinkedList<SubjectDTO> subjects = new LinkedList<SubjectDTO>();
		
		for (int i = 0; i < _subjects.size(); i++)
			if (_subjectTextBox.isItemSelected(i))
				subjects.add(_subjects.get(i));
		
		if (subjects.size() == 0) {
			Window.alert("Prosze wybrac przynajmniej jeden nauczany przedmiot");
			return;
		}
		
		TeacherDTO teacher = new TeacherDTO(_teacher.id,_surnameTextBox.getText(), _nameTextBox.getText(), _addressTextBox.getText(), _telephoneTextBox.getText(), _teacher.user, subjects);
		
		Const.eWywiadowkaService.registerTeacher(teacher, new AsyncCallback<TeacherRegisterMsg>() {

			@Override
			public void onFailure(Throwable caught) {
				Window.alert(caught.getMessage());
			}

			@Override
			public void onSuccess(TeacherRegisterMsg result) {
				Window.alert(result.toString());
			}
			
		});
	}
	
	public void onClick(ClickEvent event) {
		Const.FormularMessages msg = null;
		if ((msg = verifyFormular()) == Const.FormularMessages.OK)
			teacherModify();
		else
			Window.alert(msg.toString());
	}

}
